const router = require("koa-router")();
const fs = require("fs");
const path = require("path");
const koaBody = require("koa-body");

router.prefix("/uploadFile");

function handleRes(ctx, next, res) {
  if (res.status === 0) {
    ctx.body = res;
  } else {
    ctx.status = res.httpCode;
    ctx.body = res;
    // ctx.message = res.message   //本来想直接设置fetch的statusText，但是加了这句话请求就出错
  }
}

router.post(
  "/video",
  koaBody({
    multipart: true,
  }),
  async function (ctx, next) {
    const file = ctx.request.files; // 获取上传文件
    // 创建可读流
    console.log(ctx.request.files.data);
    const reader = fs.createReadStream(file.data.path);
    let filename = Date.now() + file.data.name;
    let filePath = path.join(__dirname, "../public/upload-files/myUpload") + `/${filename}`;
    // 创建可写流
    const upStream = fs.createWriteStream(filePath);
    // 可读流通过管道写入可写流
    reader.pipe(upStream);
    let res = {
      status: 0,
      httpCode: 200,
      message: "文件上传成功",
      url: "http://116.62.165.137:8888/myUpload/" + filename,
    };
    handleRes(ctx, next, res);
  }
);

module.exports = router;
